package basic_grammar

import (
	"errors"
	"fmt"
)

/*
不支持 try cath finally
defer panic recover
panic 相当于throw
recover 相当于catch
*/

func Test_error() int {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println(err)
		}
	}()

	num1 := 10
	num2 := 0
	res := num1 / num2
	return res
}

// 模拟 throw try catch
func TestError() {
	defer func() {
		err := recover()
		if err != nil {
			fmt.Println(err)
			fmt.Println("关闭数据库")
		}
	}()

	conn := connectDB("failed")
	fmt.Println(conn)
}

func connectDB(connection string) string {
	if connection == "success" {
		return "connection"
	} else {
		panic(errors.New("连接不成功"))
	}
}

// 比较好的写法
func TestError2() {
	conn, err := connectDB2("failed")
	if err != nil {
		fmt.Println(err)
		fmt.Println("关闭数据库")
		return
	}
	fmt.Println(conn)
}

func connectDB2(connection string) (string, error) {
	if connection == "success" {
		return "connection", nil
	}

	return "nil", errors.New("连接数据库不成功")

}
